import os
import re
from pymysql import *

# 测试使用
print(os.path.abspath(__file__))  # 显示当前文件的地址
print(os.getcwd())  # 显示主程序入口的地址

# 定义一个字典来储存方法的引用，key=访问路径，value=函数引用
route_dict = dict()


def route(url):
    def set_func(func):
        # 将所有函数的引用保存到字典中，后续调用
        route_dict[url] = func

        def call_func(*args, **kwargs):
            return func(*args, **kwargs)

        return call_func

    return set_func


@route("/index.py")
def index(info):
    with open(info["template"] + "/index.html", encoding="utf-8") as f:
        content = f.read()

        # 链接数据库
        con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
        cursor = con.cursor()
        sql = "select * from info;"
        cursor.execute(sql)
        # 查询数据
        data_from_mysql = cursor.fetchall()

        html = ""
        # 拼接html
        for tr_data in data_from_mysql:
            print(tr_data)
            html += "<tr>"
            for td_data in tr_data:
                html += f"<td>{td_data}</td>"

            html += """<td>
                        <input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007">
                    </td>
                    """
            html += "</tr>"
        print(html)
        content = re.sub(r"\{%content%\}", html, content)
        cursor.close()
        con.close()

        return content


@route("/center.py")
def center(info):
    with open(info["template"] + "/center.html", encoding="utf-8") as f:
        content = f.read()

        # 链接数据库
        con = connect(host='localhost', port=3306, database='stock_db', user='root', password='root', charset='utf8')
        cursor = con.cursor()
        sql = "select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join focus as f on i.id=f.info_id;"
        cursor.execute(sql)
        # 查询数据
        data_from_mysql = cursor.fetchall()

        html = ""
        # 拼接html
        for tr_data in data_from_mysql:
            print(tr_data)
            html += "<tr>"
            for td_data in tr_data:
                html += f"<td>{td_data}</td>"

            html += """<td>
                            <a type="button" class="btn btn-default btn-xs" href="/update/300268.html"> <span class="glyphicon glyphicon-star" aria-hidden="true"></span> 修改 </a>
                        </td>
                        <td>
                            <input type="button" value="删除" id="toDel" name="toDel" systemidvaule="300268">
                        </td>
                    """
            html += "</tr>"
        print(html)
        content = re.sub(r"\{%content%\}", html, content)
        cursor.close()
        con.close()
        return content


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')])
    filename = environ["PATH_INFO"]
    # 这里就直接使用文件名来通过字典映射出对应的函数引用执行函数
    try:
        return route_dict[filename](environ["info"])
    except Exception as error:
        print(error)
        return "没有找到该资源"
